package com.renli.servlet;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.renli.mapper.EmployeeMapper;
import com.renli.pojo.Employee;
import com.renli.servlet.common.BaseServlet;
import com.renli.utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/api/employee")
public class EmployeeServlet extends BaseServlet {
    // 添加员工
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取请求的输入流
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        reader.close();

        // 使用 Jackson 将 JSON 数据映射到 Employee 对象
        ObjectMapper mapper = new ObjectMapper();
        Employee employee = mapper.readValue(jsonBuilder.toString(), Employee.class);

        // 调用 EmployeeMapper 的 add 方法将员工信息添加到数据库
        try {
            boolean result = EmployeeMapper.add(employee);
            if (result) {
                // 添加成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
            } else {
                // 添加失败
                sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 删除员工
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int employeeId = Integer.parseInt(req.getParameter("id"));
        try {
            boolean result = EmployeeMapper.delete(employeeId);
            if (result) {
                // 删除成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
            } else {
                // 删除失败
                sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 更新员工信息
    public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取请求的输入流
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        reader.close();

        // 使用 Jackson 将 JSON 数据映射到 Employee 对象
        ObjectMapper mapper = new ObjectMapper();
        Employee employee = mapper.readValue(jsonBuilder.toString(), Employee.class);

        try {
            boolean result = EmployeeMapper.update(employee);
            if (result) {
                // 更新成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
            } else {
                // 更新失败
                sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 根据员工ID获取员工信息
    public void getEmployeeById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int employeeId = Integer.parseInt(req.getParameter("employeeId"));
        try {
            Employee employee = EmployeeMapper.getEmployeeById(employeeId);
            if (employee != null) {
                // 获取成功
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, employee));
            } else {
                // 员工不存在
                sendJsonResponse(resp, new ApiResult<>(1, "员工不存在", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 分页查询员工列表（根据员工全名模糊搜索）
    public void getEmployeesByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fullName = req.getParameter("searchParams");
        int pageNum = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("limit"));

        try {
            List<Employee> employees = EmployeeMapper.getEmployeesByPage(fullName, pageNum, pageSize);
            int totalRecordCount = EmployeeMapper.getTotalEmployeeCount(); // 获取记录总数

            if (totalRecordCount > 0) {
                // 查询成功，返回记录总数和员工列表
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", totalRecordCount, employees));
            } else {
                // 员工不存在
                sendJsonResponse(resp, new ApiResult<>(1, "员工不存在", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }


    // 批量删除员工
    public void deleteBatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 从请求的输入流中获取JSON数据
            BufferedReader reader = req.getReader();
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }

            // 使用 Jackson 将 JSON 数据解析为数组
            ObjectMapper mapper = new ObjectMapper();
            List<Integer> employeeIds = mapper.readValue(jsonBuilder.toString(), new TypeReference<List<Integer>>() {
            });

            if (employeeIds != null && !employeeIds.isEmpty()) {
                boolean result = EmployeeMapper.deleteBatch(employeeIds);
                if (result) {
                    // 删除成功
                    sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, null));
                } else {
                    // 删除失败
                    sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
                }
            } else {
                // 参数错误
                sendJsonResponse(resp, new ApiResult<>(1, "参数错误", null, null));
            }
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }

    // 获取部门及入职人数报表数据
    public void getDepartmentEntryCounts(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            List<Map<String, Object>> entryCounts = EmployeeMapper.getEntryCountsByDepartment();
            if (entryCounts != null && !entryCounts.isEmpty()) {
                // 查询成功，返回部门及入职人数报表数据
                sendJsonResponse(resp, new ApiResult<>(0, "操作成功", null, entryCounts));
            } else {
                // 数据不存在
                sendJsonResponse(resp, new ApiResult<>(1, "数据不存在", null, null));
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
            sendJsonResponse(resp, new ApiResult<>(0, "操作失败", null, null));
        }
    }


}
